package com.company.learnjpa.view;

import com.company.learnjpa.model.entity.Blog;
import com.company.learnjpa.model.repository.BlogRepository;
import com.company.learnjpa.util.Helper;
import jakarta.annotation.PostConstruct;
import jakarta.faces.application.FacesMessage;
import jakarta.faces.context.FacesContext;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.primefaces.event.SelectEvent;

/**
 *
 * @author xiaolei
 */
@Named(value = "indexView")
@ViewScoped
public class IndexView implements Serializable {

    private List<Blog> blogs;
    private List<String> categories;

    @Inject
    private BlogRepository blogRepository;

    public IndexView() {
    }

    @PostConstruct
    public void init() {
        blogs = blogRepository.findAll();
        categories = blogRepository.getAllCategories();
        categories.add(0, "全部分类");
    }

    public void onSelect(SelectEvent<String> event) {
        String category = event.getObject();
        if ("全部分类".equals(category)) {
            blogs = blogRepository.findAll();
        } else {
            blogs = blogRepository
                    .findByFields(Map.of("category", category), "-publishTime");
        }
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage("tips", event.getObject()));
    }

    public String getFirst(String str) {
        return Helper.getFirst(str, 50);
    }

    public List<Blog> getBlogs() {
        return blogs;
    }

    public void setBlogs(List<Blog> blogs) {
        this.blogs = blogs;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }

}
